package com.leijingqi.filter;

import com.alibaba.fastjson2.JSON;
import com.leijingqi.pojo.Result;
import com.leijingqi.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;

import java.io.IOException;
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       //强转
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求地址
        String url = req.getRequestURI().toString();
        //放行login
        if(url.contains("login")){
            System.out.println("登陆");
            filterChain.doFilter(servletRequest,servletResponse); //放行
            return;
        }
        //获取token
        String jwt = req.getHeader("token");
        //判断令牌存在
        if(!StringUtils.hasLength(jwt)){ //不存在
            Result error = Result.error("NOT_LOGIN");
            //转换JSON
            String notLogin = JSON.toJSONString(error);
            resp.getWriter().write(notLogin);  //响应给客户端
            return;
        }
        //解析token
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e){
            e.printStackTrace();
            System.out.println("解析失败");
            Result error = Result.error("NOT_LOGIN");
            //转换JSON
            String notLogin = JSON.toJSONString(error);
            resp.getWriter().write(notLogin);  //响应给客户端
            return;
        }

        System.out.println("拦截请求");
        filterChain.doFilter(servletRequest,servletResponse); //放行
    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }
}
